package lar.system.opengl;

import java.nio.FloatBuffer;
import java.util.EmptyStackException;

import javax.microedition.khronos.opengles.GL11;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import lar.game.gamestate.GameState;
import lar.system.engine.MainProgram;
import lar.system.engine.TouchListener;
import lar.system.engine.UI;
import lar.system.network.msgParser.Message;
import lar.system.network.msgParser.Strings;

public class GLTextField implements Drawable, GLKeyHandler
{
	private float[] glPos, glDim;
	private OnChangeHandler handler;
	private GLString string;
	
	public GLTextField(int fontResourceId, float[] glPos, float[] glDim)
	{
		string = new GLString(fontResourceId, "", new float[]{glPos[0]-glDim[0]+glDim[1]/2,glPos[1]}, glDim);
		this.glPos = glPos;
		this.glDim = glDim;
		MainProgram.glSurfaceView.addTouchListener(new TouchListener() 
		{
			public void onTouchEvent(MotionEvent e) 
			{
				if(e.getAction() != MotionEvent.ACTION_UP) return;
				//MainProgram.glSurfaceView.showKeyboard();
				//MainProgram.glSurfaceView.setKeyHandler(GLTextField.this);
				showInputDialog();
				
				//else ((InputMethodManager) MainProgram.currentActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(MainProgram.glSurfaceView.getWindowToken(), 0);
			}
		}, this);
	}

	public GLTextField(int fontResourceId, float[] glPos, float[] glDim, float height)
	{
		string = new GLString(fontResourceId, "", new float[]{glPos[0]-glDim[0]+height/2,glPos[1]}, height);
		this.glPos = glPos;
		this.glDim = glDim;
		MainProgram.glSurfaceView.addTouchListener(new TouchListener() 
		{
			public void onTouchEvent(MotionEvent e) 
			{
				if(e.getAction() != MotionEvent.ACTION_UP) return;
				//((InputMethodManager) MainProgram.currentActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(MainProgram.glSurfaceView, 0);
				//MainProgram.glSurfaceView.setKeyHandler(GLTextField.this);
				//MainProgram.glSurfaceView.showKeyboard();
				showInputDialog();
				//else ((InputMethodManager) MainProgram.currentActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(MainProgram.glSurfaceView.getWindowToken(), 0);
			}
		}, this);
	}
	
	private void showInputDialog()
	{
		AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(MainProgram.currentActivity);
		dialogbuilder.setTitle("Enter Value");
    	final EditText input = new EditText(MainProgram.currentActivity);
    	dialogbuilder.setView(input);
    	input.setText(string.getAsciiString());
    	dialogbuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
    	{
	    	public void onClick(DialogInterface dialog, int whichButton) 
	    	{
	    		String value = input.getText().toString();
	    		string.SetString(value);
	    		if(handler != null) handler.onChange(string.getAsciiString());
	    	}
	    });
    	dialogbuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
    	{
    	  public void onClick(DialogInterface dialog, int whichButton) 
    	  {
    	    // Canceled.
    	  }
    	});
    	dialogbuilder.create().show();
	}
	
	public void setOnChangeHandler(OnChangeHandler handler)
	{
		this.handler = handler;
	}
	
	public boolean CheckBounds(float x, float y) 
	{
		if(x > glPos[0]+glDim[0] || x < glPos[0]-glDim[0]) return false;
		if(y > glPos[1]+glDim[1] || y < glPos[1]-glDim[1]) return false;
		return true;
	}

	public String getText()
	{
		return string.getAsciiString();
	}
	
	public void setText(String str)
	{
		UI.needRendering = true;
		string.SetString(str);
	}

	public void Draw(GL11 gl) 
	{
		gl.glEnableClientState(GL11.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
		gl.glBindTexture(GL11.GL_TEXTURE_2D, 0);
		gl.glFrontFace(GL11.GL_CW);
		gl.glVertexPointer(3, GL11.GL_FLOAT, 0, GLEmptyQuad.vertexBuffer);
		gl.glTexCoordPointer(2, GL11.GL_FLOAT, 0, GLEmptyQuad.textureBuffer);
		gl.glPushMatrix();
		gl.glTranslatef(glPos[0], glPos[1], -1.0f);
		gl.glScalef(glDim[0], glDim[1], 1.0f);
		gl.glColor4f(0.1f, 0.1f, 0.1f, 1f);
		gl.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, GLEmptyQuad.vertices.length / 3);
		gl.glColor4f(1f, 1f, 1f, 1f);
		gl.glPopMatrix();
		gl.glDisableClientState(GL11.GL_VERTEX_ARRAY);
		gl.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
		string.Draw(gl);
	}


	public void onKeyDown(int keyCode, KeyEvent event) 
	{
		//Log.d("R", "keyDown"); 
		if (event.isPrintingKey()) 
	    {
			//Log.d("R", "printingKey");
			//String str = event.getCharacters();
			//Log.d("R", "Input: " + string.getAsciiString());
			string.SetString(string.getAsciiString() + (char)event.getUnicodeChar());
	    }
		else if(event.getKeyCode() == KeyEvent.KEYCODE_DEL)
		{
			//Log.d("R", "del");
			String str = string.getAsciiString();
			string.SetString(str.length() == 0 ? new String() : str.substring(0, str.length()-1));
		}
		else if(event.getKeyCode() == KeyEvent.KEYCODE_SPACE)
		{
			string.SetString(string.getAsciiString() + ' ');
		}
		else if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
		{
			MainProgram.glSurfaceView.hideKeyboard();
		}
		if(handler != null) handler.onChange(string.getAsciiString());
	}
	
	public interface OnChangeHandler
	{
		public void onChange(String str);
	}

}
